package com.hou.cassecurity.filter;

import com.hou.cassecurity.config.CasServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyFilter extends OncePerRequestFilter {

    @Autowired
    private CasServerProperties casServerProperties;

    @Autowired
    private ServiceProperties serviceProperties;

    @Autowired
    private CasAuthenticationEntryPoint casAuthenticationEntryPoint;

    @Autowired
    private CasAuthenticationFilter casAuthenticationFilter;

    @Autowired
    private CasAuthenticationProvider casProvider;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String s = casServerProperties.getServerName()+httpServletRequest.getRequestURI().replace("/demo","");
        String param = httpServletRequest.getQueryString();
        if(param!=null && param.indexOf("?")>0){
            String realParam = param.substring(0,param.lastIndexOf("&"));
            s+="?"+realParam;
        }
        serviceProperties.setService(s);
        casAuthenticationEntryPoint.setServiceProperties(serviceProperties);
        casAuthenticationFilter.setServiceProperties(serviceProperties);
        casProvider.setServiceProperties(serviceProperties);
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
